//
//  FKOrderListVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/22.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKOrderListVC.h"
#import "FKOrderListCell.h"
#import "FKOrderListHeader.h"
#import "FKOrderListFooter.h"
#import "FKOrder.h"
#import "FKOrderDetailVC.h"
#import "FKPayMethodView.h"
#import "FKLookLogisticsVC.h"
#import "FKOrderEvaluateVC.h"
#import "FKPayPwdInputView.h"
#import "FKSetPayPwdVC.h"
#import "FKRefundDetailVC.h"

@interface FKOrderListVC ()

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) NSMutableDictionary *param;
@property(nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *emptyView;

@end

@implementation FKOrderListVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
        _param[@"pagesize"] = @(10);
    }
    return _param;
}

- (instancetype)initWithStyle:(UITableViewStyle)style
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"refreshOrderListVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"alipay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"wechatPay" object:nil];
    
    self.param[@"status"] = self.status;
    self.tableView.autoresizingMask = UIViewAutoresizingNone;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, 200)];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Emptyorder"]];
        [_emptyView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.offset(0);
            make.width.mas_equalTo(fk_adjustW(imageView.image.size.width));
            make.height.mas_equalTo(fk_adjustW(imageView.image.size.height));
        }];
        
        UILabel *label = [[UILabel alloc] init];
        [_emptyView addSubview:label];
        label.font = fk_adjustFont(16);
        label.text = @"您暂时还没有订单哦!";
        label.textColor = fkColor999999;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_bottom).offset(20);
            make.centerX.offset(0);
        }];
    }
    return _emptyView;
}

- (void)refreshData
{
    if (self.datas.count == 0) [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    FKOrder *order = self.datas[section];
    return order.goods_list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKOrderListCell *cell = [FKOrderListCell cellWith:tableView];
    FKOrder *order = self.datas[indexPath.section];
    cell.data = order.goods_list[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    return fk_adjustW(98);
    return fk_adjustW(120);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return fk_adjustW(50);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return fk_adjustW(68);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    FKOrderListHeader *header = [FKOrderListHeader sectionView:tableView];
    header.data = self.datas[section];
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    FKOrderListFooter *footer = [FKOrderListFooter sectionView:tableView];
    footer.data = self.datas[section];
    fkWeakSelf(self);
    footer.operationBlock = ^(NSString * _Nonnull title, FKOrder *order) {
        if ([title isEqualToString:@"查看详情"]) {
            if ([order.status isEqualToString:@"50"]) { // 售后详情
                FKRefundDetailVC *vc = [[FKRefundDetailVC alloc] init];
                vc.order_refund_id = order.id;
                [weakself.navigationController pushViewController:vc animated:true];
            } else {
                FKOrderDetailVC *vc = [[FKOrderDetailVC alloc] init];
                vc.order_id = order.id;
                [weakself.navigationController pushViewController:vc animated:true];
            }
        } else if ([title isEqualToString:@"立即支付"]) {
            FKPayMethodView *view = [[FKPayMethodView alloc] init];
            view.amount = order.price;
            [view show];
            fkWeakSelf(view);
            view.selectePayMethodBlock = ^(NSString * _Nonnull payType) {
                if ([payType isEqualToString:@"balance"]) {
                    if ([FKCacheTool isHasPayPwd]) { // 设置了支付密码
                        FKPayPwdInputView *pwdView = [[FKPayPwdInputView alloc] init];
                        [pwdView show];
                        pwdView.inputFinishBlock = ^(NSString *pwd) {
                            [weakself createPayInfo:payType orderSn:order.order_sn amount:order.settle_price pwd:pwd];
                        };
                    } else { // 没有设置支付密码
                        FKSetPayPwdVC *vc = [[FKSetPayPwdVC alloc] init];
                        [weakself.navigationController pushViewController:vc animated:true];
                    }
                } else {
                    [weakself createPayInfo:payType orderSn:order.order_sn amount:order.settle_price pwd:nil];
                }
                [weakview dismiss];
            };
        } else if ([title isEqualToString:@"取消订单"]) {
            [self fk_alertWithTitle:@"确定要取消订单吗？" confirm:^{
                [weakself cancelOrder:order.id];
            }];
        } else if ([title isEqualToString:@"确认收货"]) {
            [self fk_alertWithTitle:@"是否确认收货？" confirm:^{
                [weakself confirmReceive:order.id];
            }];
        } else if ([title isEqualToString:@"查看物流"]) {
            FKLookLogisticsVC *vc = [[FKLookLogisticsVC alloc] init];
            vc.orderId = order.id;
            [weakself.navigationController pushViewController:vc animated:true];
        } else if ([title isEqualToString:@"去评价"]) {
            FKOrderEvaluateVC *vc = [[FKOrderEvaluateVC alloc] init];
            vc.orderId = order.id;
            [weakself.navigationController pushViewController:vc animated:true];
        } else if ([title isEqualToString:@"删除订单"]) {
            [self fk_alertWithTitle:@"确定要删除订单吗？" confirm:^{
                [weakself deleteOrder:order.id];
            }];
        }
    };
    return footer;
}

#pragma mark - 网络请求
- (void)loadData
{
    
    self.page = 1;
    self.param[@"page"] = @(self.page);
    NSString *suffix = @"m=Home&c=OrderList&a=online_order";
    if ([self.type isEqualToString:@"2"]) {
        suffix = @"m=Home&c=OrderList&a=offline_order";
    }
    [FKHttpTool postWithSuffix:suffix param:self.param success:^(FKBaseResult *result) {
        [self.tableView.mj_header endRefreshing];
        if (result.isSuccess) {
            self.datas = [FKOrder mj_objectArrayWithKeyValuesArray:result.data[@"list"]];
            [self updateOrdersType:self.datas];
            [self.tableView reloadData];
            if (self.datas.count > 0) self.page++;
        }
        [self.tableView fk_tableViewCheckEmptyDataWithDataCount:self.datas.count emptyView:self.emptyView];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView fk_tableViewCheckEmptyDataWithDataCount:self.datas.count emptyView:self.emptyView];
    }];
}

/** 更新订单的状态，判断是不是虚拟商品订单,为了改变操作按钮的文字 */
- (void)updateOrdersType:(NSArray<FKOrder *> *)datas
{
    if ([self.type isEqualToString:@"1"]) { // 核销订单
        for (FKOrder *order in datas) {
            order.virtualOrder = true;
        }
    }
}

- (void)loadMoreData
{
    self.param[@"page"] = @(self.page);
    NSString *suffix = @"m=Home&c=OrderList&a=online_order";
    if ([self.type isEqualToString:@"2"]) {
        suffix = @"m=Home&c=OrderList&a=offline_order";
    }
    [FKHttpTool postWithSuffix:suffix param:self.param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            NSArray *newArray = [FKOrder mj_objectArrayWithKeyValuesArray:result.data[@"list"]];
            [self updateOrdersType:newArray];
            if (newArray.count > 0) {
                [self.tableView.mj_footer endRefreshing];
                NSMutableArray *array = [NSMutableArray arrayWithArray:self.datas];
                [array addObjectsFromArray:newArray];
                self.datas = array;
                [self.tableView reloadData];
                self.page++;
            } else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)cancelOrder:(NSString *)orderId
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = orderId;
    [FKHttpTool postWithSuffix:@"m=Home&c=OrderList&a=cancel_order" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"取消成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
        }
    } failure:nil];
}

- (void)deleteOrder:(NSString *)orderId
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = orderId;
    [FKHttpTool postWithSuffix:@"m=Home&c=OrderList&a=delete_order" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
        }
    } failure:nil];
}

- (void)createPayInfo:(NSString *)payType orderSn:(NSString *)orderSn amount:(NSString *)amount pwd:(NSString *)pwd
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"payment"] = payType;
    param[@"order_sn"] = orderSn;
    param[@"password"] = pwd;
    param[@"trade_type"] = @"APP";
    [FKHttpTool postWithSuffix:@"m=Home&c=Payment&a=pay" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            if ([payType isEqualToString:@"wechat"]) {
//                PayReq *req = [[PayReq alloc] init];
//                req.partnerId = result.data[@"partnerid"];
//                req.prepayId = result.data[@"prepayid"];
//                req.nonceStr = result.data[@"noncestr"];
//                req.timeStamp = [result.data[@"timestamp"] intValue];
//                req.package = result.data[@"packages"]; // 这里本来是package字段的，被蠢猪后台自作主张改成了packages，害得我查了很久
//                req.sign = result.data[@"sign"];
//                [WXApi sendReq:req];
            } else if ([payType isEqualToString:@"alipay"]) {
//                NSString *str = result.data[@"pay_info"];
//                // NOTE: 调用支付结果开始支付
//                NSString *scheme = [NSBundle mainBundle].bundleIdentifier; // 我自己直接用bundleID作为scheme了
//                [[AlipaySDK defaultService] payOrder:str fromScheme:scheme callback:nil];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
            }
        }
    } failure:nil];
}

- (void)confirmReceive:(NSString *)orderId
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"order_id"] = orderId;
    [FKHttpTool postWithSuffix:@"m=Home&c=OrderList&a=confirm_order" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"确认收货成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListVC" object:nil];
        }
    } failure:nil];
}

@end
